<?php
/**
 * 
 * @author HelloWorld
 * 2014-9-23
 * UTF-8
 */
class Cache_Adapter_Memcached extends Cache_Abstract implements Cache_Interface{
    private $mem = null;
    private $prefix = '';

    function __construct($cache_config) {
        $this->mem = new Memcached ();
        $this->prefix = empty($config ['prefix']) ? '' : $config ['prefix'];
        foreach ( $cache_config as $config ) {
            $this->mem->addserver ( $config ['host'], $config ['port'], $config ['weight'] );
        }
    
    }
    /**
     * {@inheritDoc}
     * @see Cache_Interface::set()
     */
    public function set($key, $value, $expire=600)
    {
        $obj = serialize($value);
        if($key == false){
            return false;
        }
        $result = $this->mem->replace($this->prefix.$key,$obj,$expire);
        if(!$result){
        	$result = $this->mem->set($this->prefix.$key,$obj,$expire);
        }
        return $result;
    }

    /**
     * {@inheritDoc}
     * @see Cache_Interface::get()
     */
    public function get($key)
    {
        $result = $this->mem->get($this->prefix.$key);
		if(!empty($result)){
			$result = unserialize($result);
		}
		return $result;
        
    }

    /**
     * {@inheritDoc}
     * @see Cache_Interface::delete()
     */
    public function delete($key)
    {
    	return $this->mem->delete($this->prefix.$key);
        // TODO Auto-generated method stub
    }
    
}